//
//  BDPostDetailViewController.m
//  BadBoy
//
//  Created by wen on 2017/9/5.
//  Copyright © 2017年 com.8xiong. All rights reserved.
//

#import "BDPostDetailViewController.h"
#import "BDPostDetailCell.h"
#import "BDPostCell.h"
#import "BDPostCommentCell.h"

static CGFloat detailTableViewSectionHeadHeight = 35;

@interface BDPostDetailViewController ()<UITableViewDelegate, UITableViewDataSource, BDPostCellDelegate>
{
    UIButton *selectedButton;
}
@property (nonatomic, strong) BDPostDetailModel *detailModel;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *datasource;
@end

@implementation BDPostDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _datasource = [NSMutableArray array];
    [self requestDatasource];
}

- (void)requestDatasource{
    NSString *url = [NSString stringWithFormat:@"%@post/%@", KBDBaseURL, @(self.postId)];
    
    NSString *headValid = [BDUserModel getHeaderValidation];
    RACSignal *signal = [[BDNetworkingServer yy_GET:url parameters:nil validation:headValid automaticProcessingError:YES] execute:nil];
    [signal subscribeNext:^(id  _Nullable x) {
        BDPostModel *post = [BDPostModel modelWithJSON:x];
        BDPostLayout *layout = [[BDPostLayout alloc] initWithPost:post];
        layout.isDetail = YES;
        [layout calculateHeight];
        _detailModel = [[BDPostDetailModel alloc] initWithLayout:layout];
    }];
    [signal subscribeError:^(NSError * _Nullable error) {
        [self showErrorViewWithTapBlock:^{
            
        }];
    }];
    
    NSString *url1 = [NSString stringWithFormat:@"%@post/%d/comments?page=%@&size=%@", KBDBaseURL, self.postId, self.startPage, self.pageSize];
    RACSignal *signal1 = [[BDNetworkingServer yy_GET:url1 parameters:nil validation:headValid automaticProcessingError:YES] execute:nil];
    [signal1 subscribeNext:^(id  _Nullable x) {
        self.isEnd = [x[@"is_end"] boolValue];
        self.startPage = x[@"next_page"];
        for (NSDictionary *subDic in x[@"list"]) {
            BDPostCommentModel *comment = [BDPostCommentModel modelWithJSON:subDic];
            BDPostCommentLayout *layout = [[BDPostCommentLayout alloc] initWithComment:comment];
            [_datasource addObject:layout];
        }
    }];
    [signal1 subscribeNext:^(id  _Nullable x) {
        
    }];
    
    RACSignal *merSignal = [RACSignal merge:@[signal, signal1]];
    [merSignal subscribeCompleted:^{
        if (_datasource.count) {
            [self setTableiewFooterViewStateFor:self.tableView datasourceCount:_datasource.count];
        }
        [self.tableView reloadData];
    }];
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 1;
    }
    if (_datasource.count) {
        return _datasource.count;
    }
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return _detailModel.tableViewHeight;
    }
    if (_datasource.count) {
        BDPostCommentLayout *layout = _datasource[indexPath.row];
        return layout.height;
    }
    return 200;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section != 0) {
        return detailTableViewSectionHeadHeight;
    }
    return 0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section == 1) {
        UIView *headView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"header"];
        if (headView == nil) {
            headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kBDScreenWidth, detailTableViewSectionHeadHeight)];
            
            UIView *contentView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kBDScreenWidth, detailTableViewSectionHeadHeight)];
            contentView.bottom = headView.height;
            contentView.backgroundColor = [UIColor whiteColor];
            [headView addSubview:contentView];
            
            CGFloat btnWidth = 60;
            NSArray *titleArray = @[[NSString stringWithFormat:ASLocalizedString(@"评论 %zd"), _detailModel.layout.post.commentCount],
                                    [NSString stringWithFormat:ASLocalizedString(@"赞 %zd"), _detailModel.layout.post.praiseCount]];
            
            UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, btnWidth, 2)];
            lineView.backgroundColor = [UIColor colorWithHexString:@"4d7aad"];
            lineView.bottom = contentView.height;
            lineView.left = 10;
            [contentView addSubview:lineView];
            
            for (int i = 0; i < 1 ; i++) {
                UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
                button.size = CGSizeMake(btnWidth, contentView.height);
                if (i == 1) {
                    button.right = kBDScreenWidth - 10;
                }else{
                    button.left = 10 + btnWidth * i;
                }
                button.tag = 4422 + i;
                [button setTitle:titleArray[i] forState:UIControlStateNormal];
                button.titleLabel.font = [UIFont systemFontOfSize:12];
                [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
                [contentView addSubview:button];
                if (i == 0) {
                    selectedButton = button;
                }
                [[button rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
                    if (button == selectedButton) {
                        return ;
                    }else{
                        [UIView animateWithDuration:0.3 animations:^{
                            lineView.left = button.left;
                        } completion:^(BOOL finished) {
                            selectedButton = button;
                        }];
                    }
                }];
                
            }
        }
        return headView;
    }
    return nil;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        BDPostDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:@"detailCell" forIndexPath:indexPath];
        [cell configeWithModel:_detailModel];
        return cell;
    }else{
        if (_datasource.count) {
            BDPostCommentCell *cell = [tableView dequeueReusableCellWithIdentifier:@"commentCell" forIndexPath:indexPath];
            cell.layout = _datasource[indexPath.row];
            return cell;
        }
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"emptyCell"];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"emptyCell"];
            UILabel *label = [UILabel new];
            label.text = ASLocalizedString(@"快来发表你的评论吧");
            label.textColor = [UIColor colorWithHexString:@"#767676"];
            label.font = [UIFont systemFontOfSize:14];
            label.backgroundColor = [UIColor whiteColor];
            label.frame = cell.bounds;
            [cell.contentView addSubview:label];
        }
        return cell;
    }
}

- (UITableView *)tableView{
    if (!_tableView) {
        self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, kBDTopHeight, kBDScreenWidth, kBDScreenHeight - kBDTopHeight) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorColor = [UIColor clearColor];
        _tableView.backgroundColor = [UIColor clearColor];
//        _tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kBDScreenWidth, 0.1)];
        [_tableView registerClass:[BDPostDetailCell class] forCellReuseIdentifier:@"detailCell"];
        [_tableView registerClass:[BDPostCommentCell class] forCellReuseIdentifier:@"commentCell"];
        [self.view insertSubview:_tableView atIndex:0];
    }
    return _tableView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
